import { useState, useEffect } from 'react';
import { Form, Button, message } from 'antd';
import TextArea from 'antd/es/input/TextArea';
import { prettifyJson } from '../utils/json';
import { useStyles } from './styles';

const BodyConfig: React.FC = () => {
  const { styles } = useStyles();
  const [prettyLoading, setPrettyLoading] = useState(false);

  const handlePrettify = () => {
    try {
      const raw = Form.useWatch('body', Form.useFormInstance());
      const pretty = prettifyJson(raw);
      Form.useFormInstance().setFieldsValue({ body: pretty });
    } catch {
      message.error('JSON 格式有误');
    }
  };

  return (
    <>
      <Form.Item className={styles.card}>
        <h4>Body</h4>
        <Form.Item name="body" noStyle>
          <TextArea
            rows={8}
            placeholder='{"foo":"bar"}'
            onBlur={(e) => {
              try {
                JSON.parse(e.target.value);
              } catch {
                message.warning('Body 不是合法 JSON');
              }
            }}
          />
        </Form.Item>
        <Button
          size="small"
          loading={prettyLoading}
          onClick={handlePrettify}
          style={{ marginTop: 8 }}
        >
          格式化
        </Button>
      </Form.Item>
    </>
  );
};

export default BodyConfig;
